<template>
  <div class="category-manage-page">
    <a-card title="分类管理" :bordered="false">
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <a-form layout="inline" :model="searchForm" @finish="handleSearch">
          <a-form-item label="分类名称">
            <a-input
              v-model:value="searchForm.categoryName"
              placeholder="输入分类名称"
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="描述">
            <a-input
              v-model:value="searchForm.description"
              placeholder="输入描述"
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">搜索</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-area">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            新增分类
          </a-button>
          <a-button :disabled="!selectedRowKeys.length" @click="handleBatchDelete">
            <template #icon><delete-outlined /></template>
            批量删除
          </a-button>
        </a-space>
      </div>

      <!-- 分类列表表格 -->
      <div class="table-area">
        <a-table
          :columns="columns"
          :data-source="tableData"
          :pagination="pagination"
          :loading="loading"
          :row-selection="rowSelection"
          rowKey="id"
          @change="handleTableChange"
        >
          <!-- 排序列 -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'sortOrder'">
              {{ record.sortOrder || 0 }}
            </template>

            <!-- 创建时间列 -->
            <template v-else-if="column.key === 'createTime'">
              {{ formatDate(record.createTime) }}
            </template>

            <!-- 更新时间列 -->
            <template v-else-if="column.key === 'updateTime'">
              {{ formatDate(record.updateTime) }}
            </template>

            <!-- 操作列 -->
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleEdit(record)"> 编辑 </a-button>
                <a-popconfirm title="确定删除这个分类吗？" @confirm="handleDelete(record.id)">
                  <a-button type="link" size="small" danger> 删除 </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>

    <!-- 分类编辑模态框 -->
    <a-modal
      v-model:open="editVisible"
      :title="editForm.id ? '编辑分类' : '新增分类'"
      width="400px"
      @ok="handleSaveEdit"
      :confirm-loading="editLoading"
    >
      <a-form :model="editForm" layout="vertical">
        <a-form-item
          label="分类名称"
          name="categoryName"
          :rules="[{ required: true, message: '请输入分类名称' }]"
        >
          <a-input v-model:value="editForm.categoryName" placeholder="请输入分类名称" />
        </a-form-item>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="editForm.description"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </a-form-item>

        <a-form-item label="排序" name="sortOrder">
          <a-input-number
            v-model:value="editForm.sortOrder"
            :min="0"
            :max="999"
            style="width: 100%"
            placeholder="请输入排序值"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import {
  listCategoryByPageUsingPost,
  addCategoryUsingPost,
  updateCategoryUsingPost,
  deleteCategoryUsingPost,
  deleteCategoryBatchUsingPost,
} from '@/api/pictureCategoryController.ts'
import type { TableProps, TableColumnType } from 'ant-design-vue'

// 搜索表单
const searchForm = reactive({
  categoryName: '',
  description: '',
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 选中行
const selectedRowKeys = ref<number[]>([])

// 编辑模态框
const editVisible = ref(false)
const editLoading = ref(false)
const editForm = reactive({
  id: undefined as number | undefined,
  categoryName: '',
  description: '',
  sortOrder: 0,
})

// 表格列定义
const columns: TableColumnType[] = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '分类名称',
    dataIndex: 'categoryName',
    key: 'categoryName',
    ellipsis: true,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '排序',
    dataIndex: 'sortOrder',
    key: 'sortOrder',
    width: 100,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    sorter: true,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: 180,
    sorter: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    align: 'center',
    fixed: 'right',
  },
]

// 行选择配置
const rowSelection = computed<TableProps['rowSelection']>(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: number[]) => {
    selectedRowKeys.value = keys
  },
}))

// 获取分类列表
const fetchCategoryList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      categoryName: searchForm.categoryName,
      description: searchForm.description,
    }

    const res = await listCategoryByPageUsingPost(params)
    if (res.data.code === 0) {
      tableData.value = res.data.data?.records || []
      pagination.total = res.data.data?.total || 0
    } else {
      message.error(res.data.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    message.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchCategoryList()
}

// 重置搜索
const handleReset = () => {
  searchForm.categoryName = ''
  searchForm.description = ''
  pagination.current = 1
  fetchCategoryList()
}

// 表格变化（分页、排序）
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchCategoryList()
}

// 新增分类
const handleAdd = () => {
  editForm.id = undefined
  editForm.categoryName = ''
  editForm.description = ''
  editForm.sortOrder = 0
  editVisible.value = true
}

// 打开编辑模态框
const handleEdit = (record: any) => {
  editForm.id = record.id
  editForm.categoryName = record.categoryName
  editForm.description = record.description
  editForm.sortOrder = record.sortOrder || 0
  editVisible.value = true
}

// 保存编辑
const handleSaveEdit = async () => {
  if (!editForm.categoryName.trim()) {
    message.warning('请输入分类名称')
    return
  }

  editLoading.value = true
  try {
    const params = {
      categoryName: editForm.categoryName,
      description: editForm.description,
      sortOrder: editForm.sortOrder,
    }

    let res
    if (editForm.id) {
      // 编辑
      res = await updateCategoryUsingPost({
        id: editForm.id,
        ...params,
      })
    } else {
      // 新增
      res = await addCategoryUsingPost(params)
    }

    if (res.data.code === 0) {
      message.success(editForm.id ? '编辑成功' : '新增成功')
      editVisible.value = false
      await fetchCategoryList() // 重新获取列表数据
    } else {
      message.error(res.data.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    message.error('操作失败')
  } finally {
    editLoading.value = false
  }
}

// 删除分类
const handleDelete = async (id: number) => {
  try {
    const res = await deleteCategoryUsingPost({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      await fetchCategoryList()
    } else {
      message.error(res.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的分类')
    return
  }

  try {
    loading.value = true
    const res = await deleteCategoryBatchUsingPost({
      id: selectedRowKeys.value,
    })

    if (res.data.code === 0) {
      message.success('批量删除成功')
      // 清空选中项
      selectedRowKeys.value = []
      // 重新获取列表数据
      await fetchCategoryList()
    } else {
      message.error(res.data.message || '批量删除失败')
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    message.error('批量删除失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchCategoryList()
})
</script>

<style scoped>
.category-manage-page {
  padding: 24px;
}

.search-area {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.action-area {
  margin-bottom: 16px;
}

.table-area {
  margin-top: 16px;
}
</style>
